package model;

import app.App;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SaleRecord {

    int saleid;
    int serialNum;
    int cashier;
    int productId;
    String productName;
    float sellingPrice;
    int count;
    Timestamp saleTime;
    Product product;

    public int getSaleid() {
        return saleid;
    }

    public void setSaleid(int saleid) {
        this.saleid = saleid;
    }

    public int getSerialNum() {
        return serialNum;
    }

    public void setSerialNum(int serialNum) {
        this.serialNum = serialNum;
    }

    public int getCashier() {
        return cashier;
    }

    public void setCashier(int cashier) {
        this.cashier = cashier;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public float getSellingPrice() {
        return sellingPrice;
    }

    public void setSellingPrice(float sellingPrice) {
        this.sellingPrice = sellingPrice;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public Timestamp getSaleTime() {
        return saleTime;
    }

    public void setSaleTime(Timestamp saleTime) {
        this.saleTime = saleTime;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public Object[] toSaleListObjectArray() {
        return new Object[]{
                serialNum,
                User.getUser(cashier).getUserName(),
                productId,
                productName,
                String.format("%.2f", sellingPrice),
                count,
                String.format("%.2f", sellingPrice * count),
                saleTime};
    }

    @Override
    public String toString() {
        return "SaleRecord{" +
                "saleid=" + saleid +
                ", serialNum=" + serialNum +
                ", cashier=" + cashier +
                ", productId=" + productId +
                ", productName='" + productName + '\'' +
                ", sellingPrice=" + sellingPrice +
                ", count=" + count +
                ", saleTime=" + saleTime +
                ", product=" + product +
                '}';
    }

    //获取销售历史列表
    public static List<SaleRecord> getSaleRecordList() {
        List<SaleRecord> saleRecordList = new ArrayList<>();

        Connection conn;
        try {
            conn = App.dataSource.getConnection();//打开连接
            PreparedStatement ps = conn.prepareStatement("SELECT * FROM salerecord");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                SaleRecord saleRecord = new SaleRecord();
                saleRecord.setSaleid(rs.getInt(1));
                saleRecord.setSerialNum(rs.getInt(2));
                saleRecord.setCashier(rs.getInt(3));
                saleRecord.setProductId(rs.getInt(4));
                saleRecord.setProductName(rs.getString(5));
                saleRecord.setSellingPrice(rs.getFloat(6));
                saleRecord.setCount(rs.getInt(7));
                saleRecord.setSaleTime(rs.getTimestamp(8));
                System.out.println(saleRecord);
                saleRecordList.add(saleRecord);
            }
            conn.close();
            return saleRecordList;
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    //销售
    public static boolean SaleProducts(List<SaleRecord> saleRecordList) {
        Connection conn = null;
        try {
            conn = App.dataSource.getConnection();//打开连接
            conn.setAutoCommit(false);

            int saleId = SaleRecord.getNewSaleId();
            int outNum = StockOut.getNewStockOutId();
            for (SaleRecord saleRecord : saleRecordList) {
                System.out.println("售出的商品：" + saleRecord);

                //减少库存
                PreparedStatement ps_modCount = conn.prepareStatement("UPDATE `product` SET `quantity` = `quantity` - ? WHERE (`productid` = ?)");
                ps_modCount.setObject(1, saleRecord.getProduct().getQuantity());
                ps_modCount.setObject(2, saleRecord.getProduct().getProductId());
                ps_modCount.executeUpdate();

                //记录销售
                PreparedStatement ps_sale = conn.prepareStatement(
                        "INSERT INTO `salerecord` (`saleid`, `serialnum`, `cashier`, `productid`, `productname`, `sellingprice`, `count`, `saletime`) " +
                                "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                ps_sale.setObject(1, saleId);
                ps_sale.setObject(2, saleRecord.getSerialNum());
                ps_sale.setObject(3, saleRecord.getCashier());
                ps_sale.setObject(4, saleRecord.getProductId());
                ps_sale.setObject(5, saleRecord.getProductName());
                ps_sale.setObject(6, saleRecord.getSellingPrice());
                ps_sale.setObject(7, saleRecord.getCount());
                ps_sale.setObject(8, saleRecord.getSaleTime());
                ps_sale.executeUpdate();

                //记录出库
                PreparedStatement ps_addOut = conn.prepareStatement(
                        "INSERT INTO `stockout` (`stockoutid`, `productid`, `productname`, `sellingprice`,`purchaseprice`, `count`, `remark`, `stockouttime`) " +
                                "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                ps_addOut.setObject(1, outNum);
                ps_addOut.setObject(2, saleRecord.getProductId());
                ps_addOut.setObject(3, saleRecord.getProductName());
                ps_addOut.setObject(4, saleRecord.getSellingPrice());
                ps_addOut.setObject(5, saleRecord.getProduct().getPurchasePrice());
                ps_addOut.setObject(6, saleRecord.getCount());
                ps_addOut.setObject(7, "销售");
                ps_addOut.setObject(8, saleRecord.getSaleTime());
                ps_addOut.executeUpdate();

                saleId++;
                outNum++;
            }
            conn.commit();
            conn.close();
            return true;
        } catch (SQLException throwable) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            throwable.printStackTrace();
        }
        return false;
    }


    //获取一个新的销售号（一个商品）
    public static int getNewSaleId() {
        Connection conn;
        try {
            conn = App.dataSource.getConnection();//打开连接
            PreparedStatement ps = conn.prepareStatement("SELECT MAX(saleid) AS max FROM salerecord");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int max = rs.getInt("max") + 1;
                conn.close();
                return max;
            }
            conn.close();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return 1;
    }

    //获取一个新的流水号（一次交易）
    public static int getNewSerialNum() {
        Connection conn;
        try {
            conn = App.dataSource.getConnection();//打开连接
            PreparedStatement ps = conn.prepareStatement("SELECT MAX(serialnum) AS max FROM salerecord");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int max = rs.getInt("max") + 1;
                conn.close();
                return max;
            }
            conn.close();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return 1;
    }
}
